<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useAddOrEditJcMallSettingSku, useDeleteJcMallSettingSku, useGetCategoryList, useGetJcMallSettingSkuList, useGetProductList } from '@fl/api/man-api'
import { SearchTable } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

const { data: listData, isLoading: listLoading } = useGetJcMallSettingSkuList()

const { isPending, mutate } = useAddOrEditJcMallSettingSku()

const { isPending: deletePending, mutate: deleteMutate } = useDeleteJcMallSettingSku()

const { data: categoryData, isLoading: categoryLoading } = useGetCategoryList()

const { createConfirmModal } = useMessage()

const loading = computed(() => listLoading.value || categoryLoading.value || isPending.value || deletePending.value)

const cascaderProps = {
    emitPath: false,
    label: 'categoryName',
    value: 'cid',
}

const cascaderOptions = computed(() => categoryData.value || [])

const cid = ref()

const { data: productData } = useGetProductList(cid)

const selectOptions = computed(() => productData.value || [])

const tableRef = ref()

const cascaderRef = ref()

const key = ref(1)

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: '50' },
        { editRender: {}, field: 'catId', slots: { default: 'catId', edit: 'catId_edit' }, title: '推荐品类', width: '150' },
        { editRender: {}, field: 'productId1', slots: { default: 'productName1', edit: 'productId1' }, title: '推荐产品1', width: '150' },
        { editRender: {}, field: 'productId2', slots: { default: 'productName2', edit: 'productId2' }, title: '推荐产品2', width: '150' },
        { editRender: {}, field: 'productId3', slots: { default: 'productName3', edit: 'productId3' }, title: '推荐产品3', width: '150' },
        { editRender: {}, field: 'productId4', slots: { default: 'productName4', edit: 'productId4' }, title: '推荐产品4', width: '150' },
        { editRender: {}, field: 'productId5', slots: { default: 'productName5', edit: 'productId5' }, title: '推荐产品5', width: '150' },
        { editRender: {}, field: 'productId6', slots: { default: 'productName6', edit: 'productId6' }, title: '推荐产品6', width: '150' },
        { editRender: {}, field: 'productId7', slots: { default: 'productName7', edit: 'productId7' }, title: '推荐产品7', width: '150' },
        { editRender: {}, field: 'productId8', slots: { default: 'productName8', edit: 'productId8' }, title: '推荐产品8', width: '150' },
        { editRender: {}, field: 'sortOrder', slots: { edit: 'sortOrder_edit' }, title: '排序', width: '150' },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 220 },
    ],
    data: [{}],
    editConfig: {
        autoClear: false,
    },
    editRules: {
        catId: [
            { message: '请选择推荐品类', required: true, trigger: 'change' },
        ],
        productId1: [
            { message: '请选择产品', required: true, trigger: 'change' },
        ],
        sortOrder: [
            { message: '请输入排序', required: true, trigger: 'change' },
        ],
    },
    rowConfig: {
        keyField: 'id',
    },
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

async function addData() {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const record = {
        }
        const { row: newRow } = await $table.insertAt(record)
        await $table.setEditCell(newRow, 'catId')
    }
}

function editRowEvent(row: any) {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        cid.value = row.catId
        $table.setEditRow(row)
    }
}

function hasActiveEditRow(row: any) {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        return $table.isEditByRow(row)
    }
    return false
}

function clearRowEvent() {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        $table.clearEdit()
        key.value++
    }
}

function formatTableData() {
    const result = cloneDeep(listData.value ?? [])
    result.forEach((item: any) => {
        if (item.products && item.products.length) {
            item.products.forEach((child: any, index: number) => {
                // console.log(child, index)
                item[`productName${index + 1}`] = child.productName
                item[`productId${index + 1}`] = child.productId
            })
        }
    })
    return result
}

function changeCid(val: any) {
    cid.value = val
}

async function saveRowEvent(row: any) {
    const $table = tableRef.value?.tableInstance
    if ($table) {
        const errMap = await $table.validate()
        if (errMap) {
            ElMessage.error('请完善信息')
        }
        else {
            console.log(row)
            const selectProducts: any[] = []
            for (const key in row) {
                if (key.includes('productId') && row[key]) {
                    const params = {
                        bizId: row.catId,
                        bizType: 0,
                        productId: row[key],
                    }
                    selectProducts.push(params)
                }
            }
            const params = {
                catId: row.catId,
                catName: cascaderRef.value?.getCheckedNodes()?.[0]?.label,
                id: row.id.includes('row') ? '' : row.id,
                isDeleted: 0,
                products: selectProducts,
                sortOrder: row.sortOrder,
            }
            console.log('🚀 ~ saveRowEvent ~ params:', params)
            mutate(params, {
                onSuccess: () => {
                    ElMessage.success('操作成功')
                    key.value++
                },
            })
        }
    }
}

function deleteRowEvent(val: any) {
    createConfirmModal({
        content: '是否确认删除?',
        onError: () => {
            ElMessage.info('取消删除')
        },
        onSuccess: () => {
            deleteMutate(String(val.id), {
                onSuccess: () => {
                    ElMessage.success('操作成功')
                    key.value++
                },
            })
        },
    })
}
</script>

<template>
    <ElCard shadow="never">
        <SearchTable v-bind="gridOptions"
                     ref="tableRef"
                     :key="key"
                     :loading="loading"
                     :data="formatTableData()"
        >
            <template #toolbar_buttons>
                <ElButton type="primary"
                          @click="addData"
                >
                    新增配置
                </ElButton>
            </template>

            <template #catId="{ row }">
                {{ row.catName }}
            </template>

            <template #catId_edit="{ row }">
                <el-cascader ref="cascaderRef"
                             v-model="row.catId"
                             :show-all-levels="false"
                             :options="cascaderOptions"
                             :props="cascaderProps"
                             @change="changeCid"
                />
            </template>

            <template #productName1="{ row }">
                {{ row.productName1 }}
            </template>

            <template #productId1="{ row }">
                <el-select v-model="row.productId1"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName2="{ row }">
                {{ row.productName2 }}
            </template>

            <template #productId2="{ row }">
                <el-select v-model="row.productId2"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName3="{ row }">
                {{ row.productName3 }}
            </template>

            <template #productId3="{ row }">
                <el-select v-model="row.productId3"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName4="{ row }">
                {{ row.productName4 }}
            </template>

            <template #productId4="{ row }">
                <el-select v-model="row.productId4"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName5="{ row }">
                {{ row.productName5 }}
            </template>

            <template #productId5="{ row }">
                <el-select v-model="row.productId5"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName6="{ row }">
                {{ row.productName6 }}
            </template>

            <template #productId6="{ row }">
                <el-select v-model="row.productId6"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName7="{ row }">
                {{ row.productName7 }}
            </template>

            <template #productId7="{ row }">
                <el-select v-model="row.productId7"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #productName8="{ row }">
                {{ row.productName8 }}
            </template>

            <template #productId8="{ row }">
                <el-select v-model="row.productId8"
                           placeholder="请选择产品"
                           filterable
                >
                    <el-option v-for="item in selectOptions"
                               :key="item.productId"
                               :label="item.productName"
                               :value="item.productId"
                    />
                </el-select>
            </template>

            <template #sortOrder_edit="{ row }">
                <vxe-input v-model="row.sortOrder"
                           placeholder="请输入排序"
                           type="integer"
                />
            </template>

            <template #operate="{ row }">
                <template v-if="hasActiveEditRow(row)">
                    <ElButton text
                              @click="clearRowEvent"
                    >
                        取消
                    </ElButton>

                    <ElButton type="primary"
                              text
                              @click="saveRowEvent(row)"
                    >
                        保存
                    </ElButton>
                </template>

                <template v-else>
                    <ElButton text
                              @click="editRowEvent(row)"
                    >
                        编辑
                    </ElButton>

                    <ElButton type="primary"
                              text
                              @click="deleteRowEvent(row)"
                    >
                        删除
                    </ElButton>
                </template>
            </template>
        </SearchTable>
    </ElCard>
</template>
